import { defineStore } from 'pinia';
import { getAcupointTreeList } from '@/api/basedata';
import type {
  AcupointInfo,
  AcupointQueryParams,
  FlatAcupointInfo,
  AcupointType,
} from '@/types/acupoint';
import {
  flattenAcupoints,
  searchAcupoints as searchAcupointsUtil,
  findAcupointByCode,
  findAcupointByName,
  getMeridianAcupoints,
  getConcreteAcupoints,
  filterAcupointsByType,
  getAcupointStats,
} from '@/types/acupoint';

interface AcupointState {
  acupointTreeList: AcupointInfo[];
  acupointList: AcupointInfo[];
  flatAcupointList: FlatAcupointInfo[];
  loading: boolean;
  error: string | null;
}

export const useAcupointStore = defineStore('acupoint', {
  state: (): AcupointState => ({
    acupointTreeList: [],
    acupointList: [],
    flatAcupointList: [],
    loading: false,
    error: null,
  }),

  getters: {
    // 获取扁平化的穴位列表
    getFlatAcupoints: (state) => state.flatAcupointList,

    // 根据类型获取穴位
    getAcupointsByType: (state) => (type: AcupointType) =>
      state.flatAcupointList.filter((item) => item.acupointType === type),

    // 获取经络类型的穴位
    getMeridianTypes: (state) =>
      getMeridianAcupoints(state.acupointTreeList).map((item) => ({
        code: item.acupointCode,
        name: item.acupointText,
        type: item.acupointType,
        children: item.children,
      })),

    // 根据经络代码获取该经络下的穴位
    getAcupointsByMeridian: (state) => (meridianCode: string) => {
      const meridian = state.acupointTreeList.find(
        (item) => item.acupointCode === meridianCode
      );
      if (!meridian?.children) return [];

      // 递归获取所有子穴位
      const getAllChildren = (items: AcupointInfo[]): AcupointInfo[] => {
        const result: AcupointInfo[] = [];
        items.forEach((item) => {
          if (item.acupointType === 'acupoint') {
            result.push(item);
          }
          if (item.children?.length > 0) {
            result.push(...getAllChildren(item.children));
          }
        });
        return result;
      };

      return getAllChildren(meridian.children);
    },

    // 获取具体穴位（非经络）
    getConcreteAcupoints: (state) =>
      getConcreteAcupoints(state.acupointTreeList),

    // 获取穴位总数统计
    getAcupointStats: (state) => getAcupointStats(state.acupointTreeList),

    // 根据关键词搜索穴位
    searchByKeyword: (state) => (keyword: string) =>
      searchAcupointsUtil(state.flatAcupointList, keyword),
  },

  actions: {
    // 获取穴位树列表
    async fetchAcupointTreeList(force = false) {
      if (!force && this.acupointTreeList.length > 0) {
        return this.acupointTreeList;
      }

      this.loading = true;
      this.error = null;

      try {
        const res = await getAcupointTreeList();
        if (res.code === '200' && res.ok) {
          this.acupointTreeList = res.data;
          // 同时生成扁平化列表
          this.flatAcupointList = flattenAcupoints(res.data);
        } else {
          this.error = res.msg || '获取穴位树列表失败';
        }
        return res.data;
      } catch (error) {
        this.error =
          error instanceof Error ? error.message : '获取穴位树列表失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    // 根据穴位代码查找穴位信息
    findAcupointByCode(code: string): AcupointInfo | undefined {
      return findAcupointByCode(this.acupointTreeList, code);
    },

    // 根据穴位名称查找穴位信息
    findAcupointByName(name: string): AcupointInfo | undefined {
      return findAcupointByName(this.acupointTreeList, name);
    },

    // 本地搜索穴位（不调用API）
    localSearchAcupoints(keyword: string): FlatAcupointInfo[] {
      const searchResults = searchAcupointsUtil(this.flatAcupointList, keyword);
      return searchResults as FlatAcupointInfo[];
    },

    // 根据类型筛选穴位
    filterByType(type: AcupointType): FlatAcupointInfo[] {
      const filteredResults = this.flatAcupointList.filter(
        (item) => item.acupointType === type
      );
      return filteredResults;
    },

    // 清空数据
    clearData() {
      this.acupointTreeList = [];
      this.acupointList = [];
      this.flatAcupointList = [];
      this.error = null;
    },

    // 重置状态
    resetState() {
      this.clearData();
      this.loading = false;
    },
  },
});
